package com.mairuide.bill.importbill;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.mairuide._frame.base.BaseRepository;
import com.mairuide._frame.base.BaseServiceProxy;
import com.mairuide._frame.utils.JsonUtil;
import com.mairuide._frame.utils.excellistener.*;
import com.mairuide._frame.utils.sheethandler.POIFactory;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowService;
import com.mairuide.bill.titlepool.DealFlowTitlePoolService;
import com.mairuide.bill.titlepool.DealFlowTitleService;
import com.mairuide.bill.utils.AnalysisTxtUtils;
import com.mairuide.bill.utils.EncodingDetect;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.excel_rule.pojo.ExcelRule;
import com.mairuide.excel_rule.service.ExcelRuleService;
import com.mairuide.exceltitle_dict.enum2.PackageNameEnum;
import com.mairuide.exceltitle_dict.pojo.ExceltitleDict;
import com.mairuide.exceltitle_dict.service.ExceltitleDictService;
import com.mairuide.idnumber.service.IdNumberDetailService;
import com.mairuide.openaccountinfo.dao.OpenaccountInfoDao;
import com.mairuide.openaccountinfo.pojo.OpenaccountInfo;
import com.mairuide.platmanager.PlatManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.*;


/**
 * @author: zyh
 * @description:
 * @date: 2018/11/15 0015
 * @company: MRD
 */

@Service
@Transactional
public class TemplateMatchService extends BaseServiceProxy<TemplateMatching> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private TemplateMatchRepository templateMatchRepository;
    @Resource
    private DealFlowTitlePoolService dealFlowTitlePoolService;
    @Autowired
    AnalysisTxtUtils analysisTxtUtils;
    @Autowired
    private DealFlowTitleService dealFlowTitleService;

    @Autowired
    DealFlowService dealFlowService;
    @Override
    protected BaseRepository<TemplateMatching> getBaseRepository() {
        return templateMatchRepository;
    }
    @Resource
    private DataOperationLogService dataOperationLogService;

    @Autowired
    IdNumberDetailService idNumberDetailService;
    @Autowired
    OpenaccountInfoDao openaccountInfoDao;
    @Autowired
    ExcelRuleService excelRuleService;
    @Autowired
    ExceltitleDictService exceltitleDictService;
    @Autowired
    SpecialTemplate specialTemplate;
    public TemplateMatching findByMatchingTitle(String colData){
      return   templateMatchRepository.findByMatchingTitle(colData);

    }

    public Map<String, Object> importExcelTemplete(MultipartFile file,String uid,PlatManager platManager,String uuid) throws Exception{
//        // 解析
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<DealFlow> list = null;
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("uuid",uuid);
        paraMap.put("uid",uid);
        paraMap.put("platManagerId",platManager.getId());
        Map<String,Object> resultMap = saxAnalysis(file,uid,paraMap);
        Integer size = (Integer) resultMap.get("successNum");
        String filename = file.getOriginalFilename().split("\\.")[0];
        
        if (size==null&&!filename.equals("开户基本信息表")){ //等于0说明不是资金查控平台的excel
        	if(file.getSize()>20*1048576) {
        		resultMap = saxAnalysisDefault(file,uid,paraMap);
        		size = (Integer) resultMap.get("successNum");
        	}else {
                wb = ExcelUtils.readExcel(file);
                temp:if (wb != null) {
                    // 获取第一个sheet
                    if ("新一代个人账户信息".equals(wb.getSheetName(0))){
                        list = dealFlowTitleService.ccbNewTemplate(wb);
                        break temp;
                    }
                    if ("企业账户信息".equals(wb.getSheetName(0))){
                        list = dealFlowTitleService.xiguTemplate(wb);
                        break temp;
                    }
                    if (wb.getNumberOfSheets()>1&&"旧核心交易流水(1)".equals(wb.getSheetName(1))){
                        list = dealFlowTitleService.guangFaTemplate(wb);
                        break temp;
                    }
                    sheet = wb.getSheetAt(0);
                    // 获取最大行数
                    int rownum = sheet.getLastRowNum();
                    String matchingTitle = null;
                    // 取得导入文件中的标题头数据以,分割(如 : ,交易日期,类型,户名)
                    String colData = "";
                    for (int i = 0; i < rownum; i++) {
                        row = sheet.getRow(i);
                        if (ExcelUtils.isBlankLine(row)&&"根 据 实 名 证 件 查 账 号 / 卡 号 ( 司 法 )".equals(ExcelUtils.getCellValue(row.getCell(0)).trim())){
                            list = dealFlowTitleService.youZhengTemplate(wb);
                            break temp;
                        }
                        if (!ExcelUtils.isBlankLine(row)) continue;
                        if (ExcelUtils.isMergedRegion(sheet, i, 3)) continue;
                        if ("".equals(ExcelUtils.getCellValue(row.getCell(3)).trim())) continue;
                        if (ExcelUtils.getCellValue(row.getCell(0)).indexOf("：") > 0) continue;
                        // 获取列数
                        int physicalNumberOfCells = row.getPhysicalNumberOfCells();
                        if (physicalNumberOfCells > 6) {
                            for (int j = 0; j < physicalNumberOfCells; j++) {
                                colData += row.getCell(j) + ",";
                            }
                            break;
                        }
                    }
                    String methods = null;
                    // 根据数据库标题头表进行匹配
                    TemplateMatching allByMatchingTitle = findByMatchingTitle(colData);
                    if (allByMatchingTitle != null) {
                        // 获取模板对应导入方法
                        methods = allByMatchingTitle.getMethods();
                    }
                    if (methods != null) {
                        Class<?> clazz = Class.forName("com.mairuide.bill.utils.AnalysisTempBillUtils");
                        Method method = clazz.getMethod(methods, Workbook.class,String.class);
                        list = (List<DealFlow>) method.invoke(clazz.newInstance(), wb,filename);
                        for (DealFlow dd:list){
                            dd.setTemplateTag(methods);
                        }
                    } else {
                        // 去标题池匹配
                        list = dealFlowTitlePoolService.leadBillByTitlePoolExcel(wb);
                    }
                }
        	}
        }
        if (size==null&&list!=null&&!filename.equals("开户基本信息表")){
            for (int i=0;i<list.size();i++){
                DealFlow dealFlow = list.get(i);
                dealFlow.setUuid(uuid);
                dealFlow.setCasemanageId(uid);
                dealFlow.setCreateId(platManager.getId());
                dealFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
                dealFlow.setIsDelete(0);

            }
            List<DealFlow> temp = new ArrayList<DealFlow>();
            for(int i=0;i<list.size();i++) {
                temp.add(list.get(i));
                if(i==list.size()-1 || i%500==499) {
                    dealFlowService.batchSave(temp);
                    temp = new ArrayList<DealFlow>();
                }
            }
            size=list.size();
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("successNum", size);
//        map.put("list", list);
        return map;
    }

    /**
     *
     * @author 刘中华
     * @date 2018/11/21 14:51
     * @param [file]
     * @return java.util.Map
     * @Description 解析txt的方法
     */
    public Map<String,Object> importTxtTemplete(MultipartFile file,String uid,Integer id,String uuid) throws Exception{
        //查看属于哪个编码格式
        File f = new File("d://temp.txt");
        file.transferTo(f);
        HashMap<String, Object> map = new HashMap<>();
        String javaEncode = EncodingDetect.getJavaEncode(f);
        if("BIG5".equals(javaEncode)){
            javaEncode="gb2312";
        }
        //得到属于哪个txt模板
        String whichTemplete = getWhichTemplete(file,javaEncode);
        List<DealFlow> list=null;
        OpenaccountInfo open=null;
        if (whichTemplete==null){
            map.put("successNum", 0);
            return map;
        }
        if (whichTemplete.equals("nanYang")){
            list = analysisTxtUtils.analysisNanYangTxt(file);
        }else if (whichTemplete.equals("youZheng")){
            list = analysisTxtUtils.analysisYouZhengTxt(file,javaEncode);
        }else if (whichTemplete.equals("shengNongHang")){
            list = analysisTxtUtils.analysisShengNongTingTxt(file,javaEncode);
        }else if (whichTemplete.equals("shengNongHang1")){
            list = analysisTxtUtils.analysisShengNong1TingTxt(file,javaEncode);
        }else if (whichTemplete.equals("shengNongHang2")){
            list = analysisTxtUtils.analysisShengNong2TingTxt(file,javaEncode);
        }else if (whichTemplete.equals("kaiFeng")){
            list = analysisTxtUtils.analysisKaiFengTxt(file,javaEncode);
        }else if (whichTemplete.equals("pingAn")){
            list = analysisTxtUtils.analysisPingAnTxt(file,javaEncode);
        }else if (whichTemplete.equals("pingDingshan")){
            list = analysisTxtUtils.analysisPingDingShanTxt(file,javaEncode);
        }else if (whichTemplete.equals("nongShang")){
            list = analysisTxtUtils.analysisNongShangTxt(file,javaEncode);
        }else if (whichTemplete.equals("nongHang")){
            list = analysisTxtUtils.analysisHongHangTxt(file,javaEncode);
        }else if (whichTemplete.equals("zhongHangDuiGong")){
            list = analysisTxtUtils.analysisZhongHangDuiGongTxt(file,javaEncode);
        }else if (whichTemplete.equals("nong")){
            list = analysisTxtUtils.analysisNongTxt(file,javaEncode);
        }else if (whichTemplete.equals("zhudangchaxun")){
            list = analysisTxtUtils.zhuDangChaxun(file,javaEncode);
        }else if (whichTemplete.equals("weigongjincha")){
            list = analysisTxtUtils.zZGongAn(file,javaEncode);
        }else if (whichTemplete.equals("weixin")){
            list = analysisTxtUtils.weiXin(file,javaEncode);
        }else if (whichTemplete.equals("weixinInfo")){
            open = analysisTxtUtils.weiXinInfo(file,javaEncode);
        }else if (whichTemplete.equals("nonghangATM")){
            list = analysisTxtUtils.nongHangAtm(file,javaEncode);
        }

        int successNum = 0;
        if (list!=null) {
            for (int i = 0; i < list.size(); i++) {
                DealFlow dealFlow = list.get(i);
                dealFlow.setCasemanageId(uid);
                dealFlow.setUuid(uuid);
                dealFlow.setCreateId(id);
                dealFlow.setIsDelete(0);
                dealFlow.setCreateTime(new Timestamp(System.currentTimeMillis()));
                if(StringUtils.isEmpty(dealFlow.getAccountBodyCard()) && StringUtils.isEmpty(dealFlow.getAccountBodyNumber())) {
                	list.remove(dealFlow);
                }
            }
            List<DealFlow> temp = new ArrayList<DealFlow>();
            for (int i = 0; i < list.size(); i++) {
                temp.add(list.get(i));
                if (i == list.size() - 1 || i % 500 == 499) {
                    dealFlowService.batchSave(temp);
                    temp = new ArrayList<DealFlow>();
                }
            }
            successNum = list.size();
        }else if (open!=null){
            open.setCasemanageId(uid);
            successNum = 1;
            openaccountInfoDao.save(open);
        }

        map.put("successNum", String.valueOf(successNum));
//        map.put("list", list);
        return  map;
    }
    /**
    *
    * @author 刘中华
    * @date 2018/11/21 14:51
    * @param [file]
    * @return java.util.Map
    * @Description 解析txt的方法
    */
   public Map<String,Object> importTxtTempleteMapping(MultipartFile file,String uid,Integer id,String uuid) throws Exception{
       //查看属于哪个编码格式
       File f = new File("d://temp.txt");
       file.transferTo(f);
       String javaEncode = EncodingDetect.getJavaEncode(f);
       if("BIG5".equals(javaEncode)){
           javaEncode="gb2312";
       }
       //得到属于哪个txt模板
       String whichTemplete = getWhichTemplete(file,javaEncode);
       List<DealFlow> list=null;
       OpenaccountInfo open=null;
       if (whichTemplete==null){
           throw new Exception();
       }
       if (whichTemplete.equals("nanYang")){
           list = analysisTxtUtils.analysisNanYangTxt(file);
       }else if (whichTemplete.equals("youZheng")){
           list = analysisTxtUtils.analysisYouZhengTxt(file,javaEncode);
       }else if (whichTemplete.equals("shengNongHang")){
           list = analysisTxtUtils.analysisShengNongTingTxt(file,javaEncode);
       }else if (whichTemplete.equals("kaiFeng")){
           list = analysisTxtUtils.analysisKaiFengTxt(file,javaEncode);
       }else if (whichTemplete.equals("pingAn")){
           list = analysisTxtUtils.analysisPingAnTxt(file,javaEncode);
       }else if (whichTemplete.equals("pingDingshan")){
           list = analysisTxtUtils.analysisPingDingShanTxt(file,javaEncode);
       }else if (whichTemplete.equals("nongShang")){
           list = analysisTxtUtils.analysisNongShangTxt(file,javaEncode);
       }else if (whichTemplete.equals("nongHang")){
           list = analysisTxtUtils.analysisHongHangTxt(file,javaEncode);
       }else if (whichTemplete.equals("zhongHangDuiGong")){
           list = analysisTxtUtils.analysisZhongHangDuiGongTxt(file,javaEncode);
       }else if (whichTemplete.equals("nong")){
           list = analysisTxtUtils.analysisNongTxt(file,javaEncode);
       }else if (whichTemplete.equals("zhudangchaxun")){
           list = analysisTxtUtils.zhuDangChaxun(file,javaEncode);
       }else if (whichTemplete.equals("weigongjincha")){
           list = analysisTxtUtils.zZGongAn(file,javaEncode);
       }else if (whichTemplete.equals("weixin")){
           list = analysisTxtUtils.weiXin(file,javaEncode);
       }else if (whichTemplete.equals("weixinInfo")){
           open = analysisTxtUtils.weiXinInfo(file,javaEncode);
       }else if (whichTemplete.equals("nonghangATM")){
           list = analysisTxtUtils.nongHangAtm(file,javaEncode);
       }

       HashMap<String, Object> map = new HashMap<>();
       map.put("data", list);
       return map;
   }
    /**
     *
     * @author 刘中华
     * @date 2018/11/22 14:06
     * @param [file, javaEncode]
     * @return java.lang.String
     * @Description 获取属于哪个模板
     */
    public String getWhichTemplete(MultipartFile file , String javaEncode){
        String which=null;
        InputStream inputStream=null;
        InputStreamReader reader=null;
        BufferedReader br=null;
        String nanYang="查询账号|内部结算账号|交易日期|交易时间|交易金额|交易后余额|交易产品号|对方账号及户名|传票号|日志号|交易码|交易行号|交易地点|摘要";
        String youZheng="一本通/绿卡通交易明细(司法)";
        String shengNongHang="帐号交易产品号交易日期交易时间交易代码传票号";
        String shengNongHang1="交易日期付款方账号付款方姓名";
        String kaiFeng="交易机构号交易机构名称户名账号摘要交易金额余额对方账号卡号对方户名交易日期交易时间交易柜员";
        String pingAn="个人账户汇总信息清单";
        String pingDingshan="公检法查询个人客户信息";
        String nongShang = "交易机构号交易机构名称户名账号摘要交易金额余额对方账号卡号对方户名交易日期交易时间交易柜员";
        String nongHang="证件号码|证件类型|客户号|姓名|账户|关联账号|账户类型|账户余额|开户日期|销户日期|账户状态";
        String zhongHangDuiGong = "交易账号|交易日期|交易流水号|外围系统uuid|产品大类|产品子类|产品描述|账户属性|客户类别|账户类型|卡号|交易性质|交易属性|交易类型|交易类型描述|交易时间|交易柜员|交易机构号|交易机构名称|原子交易码|原始交易码|提示码|提示码描述|交易渠道|交易货币|交易货币英文码|交易汇率|借贷标识|冲正标识|交易金额|交易后余额|交易后可用余额|备注|用途|附言|摘要|真实付款人账户名称|真实付款人卡号|真实付款人账号|真实付款人子账户类别号|真实付款人册号|真实付款人序号|真实付款人账号所属机构名称|真实付款人账号所属机构号|真实付款人账户省联行号|真实收款人账户名称|真实收款人卡号|真实收款人账号|真实收款人子账户类别号|真实收款人册号|真实收款人序号|真实收款人所属机构名称|真实收款人账户所属机构号|真实收款人账户省联行号|客户号|跨行标识|异地标识";
        String weixin = "用户ID交易单号借贷类型交易类型交易金额（分）账户余额交易时间银行类型交易说明商户名称发送方发送金额（分）接收方接收时间接收金额（分）";
        String weixinInfo = "账户状态账号注册姓名注册时间注册身份证号绑定手机绑定状态开户行信息银行账号";
        String nonghangATM = "收付|账号|对方账号|交易日期|交易代码|交易金额|终端号|请求流水号|应答流水号";
        try {
            inputStream = file.getInputStream();
            reader= new InputStreamReader(inputStream,javaEncode);
            br = new BufferedReader(reader);
            String text = null;
            int i = 0;//记录标题在第几行
            while((text = br.readLine()) != null){
                if (nanYang.equals(text.trim())){
                    which = "nanYang";
                    break;
                }else if (youZheng.equals(text)){
                    which = "youZheng";
                    break;
                }else if (shengNongHang.equals(text.replaceAll("\\s+",""))){
                    if ("交易金额交易后余额交易地点".equals(br.readLine().replaceAll("\\s+",""))){
                        which = "shengNongHang";
                    }else {
                        which = "shengNongHang2";
                    }
                    break;
                }else if (shengNongHang1.equals(text.replaceAll("\\s+",""))){
                    which = "shengNongHang1";
                    break;
                }else if (i==0&&kaiFeng.equals(text.replaceAll("\\s+",""))){
                    which = "kaiFeng";
                    break;
                }else if (pingAn.equals(text.replaceAll("\\s+",""))){
                    which = "pingAn";
                    break;
                }else if (pingDingshan.equals(text.replaceAll("\\s+",""))){
                    which = "pingDingshan";
                    break;
                }else if (i==2&&nongShang.equals(text.replaceAll("\\s+",""))){
                    which = "nongShang";
                    break;
                }else if (nongHang.equals(text.replaceAll("\\s+",""))){
                    which = "nongHang";
                    break;
                }else if (zhongHangDuiGong.equals(text.replaceAll("\\s+",""))){
                    which = "zhongHangDuiGong";
                    break;
                }else if ("单位户交易明细查询".equals(text.trim())){
                    which = "nong";
                    break;
                }else if ("主档信息查询：".equals(text.trim())){
                    which = "zhudangchaxun";
                    break;
                }else if (text.trim().startsWith("查询的户名（账号）：")){
                    which = "weigongjincha";
                    break;
                }else if (weixin.equals(text.replaceAll("\\s+",""))){
                    which = "weixin";
                    break;
                }else if (weixinInfo.equals(text.replaceAll("\\s+",""))){
                    which = "weixinInfo";
                    break;
                }else if (nonghangATM.equals(text.replaceAll("\\s+",""))){
                    which = "nonghangATM";
                    break;
                }
                i++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            AnalysisTxtUtils.closeStream(inputStream,reader,br);
            return which;
        }
    }

    /**
     *
     * @author 刘中华
     * @date 2019/1/8 11:01
     * @param [file]
     * @return void
     * @Description 解析大文件的excel。
     */
    public Map<String,Object>  saxAnalysis(MultipartFile file,String caseManageId,Map<String , Object> paramMap) throws Exception{
        List<DealFlow> list=new ArrayList<DealFlow>();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        String filename = file.getOriginalFilename().split("\\.")[0];
        InputStream inputStream = file.getInputStream();
        try {
            if ("资金查控平台".equals(filename)){//如果是这种模板的资金查控平台走这种解析方式
                InputStream inputStream2 = file.getInputStream();
                ZJGKPTExcelListener excelListener = new ZJGKPTExcelListener(dealFlowService);
                ZJGKPTExcelListener2 excelListener2 = new ZJGKPTExcelListener2(idNumberDetailService);
                EasyExcelFactory.readBySax(inputStream,new com.alibaba.excel.metadata.Sheet(2, 0), excelListener);
                EasyExcelFactory.readBySax(inputStream2,new com.alibaba.excel.metadata.Sheet(3, 0), excelListener2);
                list=excelListener.getList();
            }else if (filename.contains("开户基本信息")){//如果是这种模板保存到其他表
                //List<OpenaccountInfo> openAccountInfoList=openaccountInfoDao.findByCasemanageId(caseManageId);
                //List<String> TradeCardcollect = openAccountInfoList.stream().map(m -> m.getTradeCard()).collect(Collectors.toList());
                OpenAccountInfoExcelListener excelListener = new OpenAccountInfoExcelListener();
                excelListener.setParaMap(paramMap);
                //excelListener.setTradeCardcollect(TradeCardcollect);
                EasyExcelFactory.readBySax(inputStream,new com.alibaba.excel.metadata.Sheet(1, 0), excelListener);
                resultMap=excelListener.getResultMap();
            }else if (filename.contains("账户交易明细")||filename.contains("MRD")){
                BaseDealFlowExcelListener excelListener = new BaseDealFlowExcelListener();
                /*EasyExcelFactory.readBySax(inputStream,new com.alibaba.excel.metadata.Sheet(1, 0), excelListener);
                list=excelListener.getList();*/
                excelListener.setParaMap(paramMap);
                ExcelReader excelReader = EasyExcelFactory.getReader(new BufferedInputStream(inputStream),excelListener);
                List<com.alibaba.excel.metadata.Sheet> sheets = excelReader.getSheets();
                for (int i=0;i<sheets.size();i++) {
                    excelReader.read(sheets.get(i));
                }
                inputStream.close();
                resultMap=excelListener.getResultMap();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return resultMap;
        }

    }
    /**
     *
     * @author songRT
     * @date 2019/1/8 11:01
     * @param [file]
     * @return void
     * @Description 解析大文件的excel。匹配标题池的通用模板
     */
    public Map<String,Object> saxAnalysisDefault(MultipartFile file,String caseManageId,Map<String , Object> paramMap) throws Exception{
//    	List<DealFlow> list=new ArrayList<DealFlow>();
    	Map<String,Object> resultMap = new HashMap<String,Object>();
//    	String filename = file.getOriginalFilename().split("\\.")[0];
    	InputStream inputStream = file.getInputStream();
    	try {
    		DefaultDealFlowExcelListener excelListener = new DefaultDealFlowExcelListener();
    		excelListener.setParaMap(paramMap);
			ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener);
			List<com.alibaba.excel.metadata.Sheet> sheets = excelReader.getSheets();
			for (int i=0;i<sheets.size();i++) {
				excelReader.read(sheets.get(i));
			}
			inputStream.close();
			resultMap=excelListener.getResultMap();
    			/*BaseDealFlowExcelListener excelListener = new BaseDealFlowExcelListener();
    			excelListener.setParaMap(paramMap);
    			ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener);
    			List<com.alibaba.excel.metadata.Sheet> sheets = excelReader.getSheets();
    			for (int i=0;i<sheets.size();i++) {
    				excelReader.read(sheets.get(i));
    			}
    			inputStream.close();
    			resultMap=excelListener.getResultMap();*/
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		return resultMap;
    	}
    	
    }



    /**
     * @Author 刘中华
     * @Date 2019/4/10 16:39
     * @Param
     * @return 通用的解析方法，最终版。智能模板匹配
     * @Description
     **/
    public Map<String, Object> xxx(MultipartFile file,Map<String , Object> paramMap) throws Exception{
        Map<String, Object> resultMap = new HashMap<>();
        String filename = file.getOriginalFilename();
        paramMap.put("excelName",filename);
        InputStream inputStream = new BufferedInputStream(file.getInputStream());
        InputStream inputStream2=null;
        InputStream inputStream3=null;
        if (filename.contains("账户交易明细") || filename.contains("涉案人员交易明细")){
            try {
                resultMap = POIFactory.deal(file.getInputStream(),paramMap);
            } catch (OLE2NotOfficeXmlFileException e) {
                e.printStackTrace();
                resultMap.put("errorInfo","(excel格式错误，请把excel打开另存为xlsx格式)");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (resultMap==null||!resultMap.containsKey("successNum")){
            if (filename.contains("开户基本信息") || filename.contains("涉案人员开户信息")) {
                OpenAccountInfoExcelListener excelListener = new OpenAccountInfoExcelListener();
                excelListener.setParaMap(paramMap);
                EasyExcelFactory.readBySax(inputStream,new com.alibaba.excel.metadata.Sheet(1, 0), excelListener);
                resultMap=excelListener.getResultMap();
            }else if(filename.contains("客户基本信息")) {
            	CustomerInformationExcelListener custListener = new CustomerInformationExcelListener();
            	custListener.setParaMap(paramMap);
            	EasyExcelFactory.readBySax(inputStream,new com.alibaba.excel.metadata.Sheet(1, 0), custListener);
                resultMap=custListener.getResultMap();
            }else{
                CommonDealFlowExcelListener excelListener = new CommonDealFlowExcelListener();
                excelListener.setParaMap(paramMap);
                //第一步，先查找出来对应的ExcelRule,每个sheet对应一个规则，因为到后面发现有的excel的不同sheet中标题头不一样
                AnalysisExcelRuleExcelListener excelListenerSheet = new AnalysisExcelRuleExcelListener();
                excelListenerSheet.setFilename(filename);
                ExcelReader excelReaderxx = EasyExcelFactory.getReader(inputStream,excelListenerSheet);
                List<com.alibaba.excel.metadata.Sheet> sheetsxx = null;
                try {
                    sheetsxx = excelReaderxx.getSheets();
                } catch (ExcelAnalysisException e) {
                    resultMap.put("errorInfo","(excel格式错误，请把excel打开另存为xlsx格式)");
                    e.printStackTrace();
                }
                if (sheetsxx!=null){
                    for (int k=0;k<sheetsxx.size();k++) {
                        excelReaderxx.read(sheetsxx.get(k));
                        ExcelRule excelRule = excelListenerSheet.getExcelRule();
                        logger.info("文件名："+filename+"，第"+k+"个sheet"+sheetsxx.get(k).getSheetName()+":::"+excelRule);
                        if (excelRule!=null){
                            //第二步 再查出exceltitleDict
                            String titleHead = excelRule.getTitleHead();
                            String[] split = titleHead.split(",");
                            List<String> titleHeadList = Arrays.asList(split);
                            Map<Integer, ExceltitleDict> exceltitleDictByTitleHead = exceltitleDictService.getExceltitleDictByTitleHead(titleHeadList, PackageNameEnum.DEALFLOW.getPackageName());
                            excelListener.setExceltitleDictMap(exceltitleDictByTitleHead);
                            excelListener.setExceltitleDictMapBak(exceltitleDictByTitleHead);
                            excelListener.setExcelRule(excelRule);
                            //第三步 读取excel
                            inputStream2 = new BufferedInputStream(file.getInputStream());
                            ExcelReader excelReader = EasyExcelFactory.getReader(inputStream2,excelListener);
                            List<com.alibaba.excel.metadata.Sheet> sheets = excelReader.getSheets();
                            for (int i=0;i<sheets.size();i++) {
                                if (k!=i) continue;
                                //说明是多sheet文件
                                if (excelRule.getIsMultiSheet()!=null&&excelRule.getIsMultiSheet()==1){
                                    String multiSheetDetail = excelRule.getMultiSheetDetail();
                                    Map<String,Object> string2Map = JsonUtil.string2Obj(multiSheetDetail, Map.class);
                                    Integer type = Integer.valueOf(string2Map.get("type").toString());
                                    List<Map<String, Object>> obj = (List<Map<String, Object>>)string2Map.get("obj");
                                    if (type==1){//1是数据库配置的包含那个sheet名字就解析那个sheet
                                        for (int j = 0; j < obj.size(); j++) {
                                            Map<String, Object> map1 = obj.get(j);
                                            String sheetName = map1.get("sheetName").toString();
                                            if (sheetName.equals(sheets.get(i).getSheetName())){
                                                excelReader.read(sheets.get(i));
                                            }
                                        }
                                    }
                                }else{
                                    excelReader.read(sheets.get(i));
                                }
                                excelListenerSheet.setExcelRule(null);
                            }
                        }
                    }
                    resultMap = excelListener.getResultMap();
                }
                inputStream.close();
                if (inputStream2!=null){
                    inputStream2.close();
                }
                if (inputStream3!=null){
                    inputStream3.close();
                }
            }
        }
        if (resultMap==null||!resultMap.containsKey("successNum")){
            //最简单的模板
            try {
                resultMap = POIFactory.deal(file.getInputStream(),paramMap);
            }catch (OLE2NotOfficeXmlFileException e) {
                e.printStackTrace();
                resultMap.put("errorInfo","(excel格式错误，请把excel打开另存为xlsx格式)");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //如果上面的没有匹配到。碰到了比较恶心的模板，比如邮政的**模板，就走这个方法。
        if(resultMap==null||!resultMap.containsKey("successNum")||Integer.valueOf(resultMap.get("successNum").toString())==0){
            Workbook wb = null;
            Sheet sheet = null;
            Row row = null;
            wb = ExcelUtils.readExcel(file);
            if (wb != null){
                sheet = wb.getSheetAt(0);
                // 获取最大行数
                int rownum = sheet.getLastRowNum();
                for (int i = 0; i < rownum; i++) {
                    row = sheet.getRow(i);
                    if (ExcelUtils.isBlankLine(row)&&("根 据 实 名 证 件 查 账 号 / 卡 号 ( 司 法 )".equals(ExcelUtils.getCellValue(row.getCell(0)).trim())||"根 据 实 名 证 件 查 账 号 / 卡 号 ( 司 法 )".equals(ExcelUtils.getCellValue(row.getCell(1)).trim()))){
                        resultMap = specialTemplate.getYouZhengTemplate(wb, paramMap);
                        if (Integer.valueOf(resultMap.get("successNum").toString())>0){
                            break;
                        }
                    }
                }
            }
        }
        /**  没有导入成功，也没有错误记录，就默认是没有找到合适的模板  */
        if (!resultMap.containsKey("successNum")&&!resultMap.containsKey("errorInfo")){
            resultMap.put("errorInfo","没有找到匹配的模板，请联系管理员新增模板");
        }
        return resultMap;
    }
}
